<template>
  <div style="width: 100%; height: 100%">
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span>招聘活动管理</span>
        <el-button type="primary" @click="createEvent" style="float: right; margin-left: 10px;">新增招聘活动</el-button>
        <el-button type="danger" @click="deleteSelectedEvents" style="float: right;">批量删除</el-button>
      </div>

      <el-table :data="eventList" ref="eventTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="title" label="活动名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="event_date" label="活动日期">
          <template slot-scope="scope">
            {{ formatDate(scope.row.event_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="event_time" label="活动时间">
<!--          <template slot-scope="scope">-->
<!--            {{ formatTime(scope.row.event_time) }}-->
<!--          </template>-->
        </el-table-column>
        <el-table-column prop="location" label="活动地点"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="editEvent(scope.row)" type="primary" size="small">编辑</el-button>
<!--            <el-button @click="sendNotification(scope.row)" type="success" size="small">发送通知</el-button>-->
            <el-button @click="deleteEvent(scope.row)" type="danger" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 招聘活动安排弹窗 -->
    <el-dialog title="安排招聘活动" :visible.sync="dialogVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="活动名称" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth" prop="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="活动日期" :label-width="formLabelWidth" prop="event_date">
          <el-date-picker v-model="form.event_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="活动时间" :label-width="formLabelWidth" prop="event_time" >
          <el-time-picker v-model="form.event_time" placeholder="选择时间" value-format="HH:mm:ss"></el-time-picker>
        </el-form-item>
        <el-form-item label="活动地点" :label-width="formLabelWidth" prop="location">
          <el-input v-model="form.location"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm('form')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      eventListByid:[],
      eventList: [],
      dialogVisible: false,
      form: {
        event_id: null,
        title: '',
        description: '',
        event_date: '',
        event_time: '',
        location: ''
      },
      user:JSON.parse(localStorage.getItem('userData')) || {},
      formLabelWidth: '120px',
      selectedEvents: [],
      rules: {
        title: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入活动描述', trigger: 'blur' }
        ],
        event_date: [
          { required: true, message: '请选择活动日期', trigger: 'change' }
        ],
        event_time: [
          { required: true, message: '请选择活动时间', trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入活动地点', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    formatDate(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      return `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`;
    },
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return `${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}:${('0' + date.getSeconds()).slice(-2)}`;
    },
    fetchEventsByid(){
      let organizer_id=this.user.user_id
      axios.get(`http://localhost:8080/events/all/${organizer_id}`)
          .then(response => {
            this.eventList = response.data.data;
          })
          .catch(error => {
            console.error('Error fetching events:', error);
          });
    },

    fetchEvents() {
      this.fetchEventsByid();
      // axios.get('http://localhost:8080/events/all')
      //     .then(response => {
      //       this.eventList = response.data.data;
      //     })
      //     .catch(error => {
      //       console.error('Error fetching events:', error);
      //     });
    },
    createEvent() {
      this.form = {
        event_id: null,
        title: '',
        description: '',
        event_date: '',
        event_time: '',
        location: '',
        organizer_id:'',
      };
      this.dialogVisible = true;
    },
    editEvent(row) {
      this.form = {...row};
      this.dialogVisible = true;
    },
    sendNotification(row) {
      this.$notify({
        title: '通知',
        message: `已向 ${row.title} 发送招聘活动通知`,
        type: 'success'
      });
    },
    deleteEvent(row) {
      axios.delete(`http://localhost:8080/events/delete/${row.event_id}`)
          .then(() => {
            this.fetchEvents();
            this.$message({
              message: '招聘活动已删除',
              type: 'success'
            });
          })
          .catch(error => {
            console.error('Error deleting event:', error);
          });
    },
    deleteSelectedEvents() {
      const deletePromises = this.selectedEvents.map(event =>
          axios.delete(`http://localhost:8080/events/delete/${event.event_id}`)
      );
      Promise.all(deletePromises)
          .then(() => {
            this.fetchEvents();
            this.$message({
              message: '选中的招聘活动已删除',
              type: 'success'
            });
          })
          .catch(error => {
            console.error('Error deleting selected events:', error);
          });
    },
    handleSelectionChange(val) {
      this.selectedEvents = val;
    },
    submitForm(formName) {
      this.form.organizer_id=this.user.user_id;
      console.log(this.form)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.form.event_id === null) {
            axios.post('http://localhost:8080/events/create', this.form)
                .then(() => {
                  this.fetchEvents();
                  this.dialogVisible = false;
                  this.$message({
                    message: '招聘活动已新增',
                    type: 'success'
                  });
                })
                .catch(error => {
                  console.error('Error creating event:', error);
                });
          } else {
            axios.put(`http://localhost:8080/events/update/${this.form.event_id}`, this.form)
                .then(() => {
                  this.fetchEvents();
                  this.dialogVisible = false;
                  this.$message({
                    message: '招聘活动已更新',
                    type: 'success'
                  });
                })
                .catch(error => {
                  console.error('Error updating event:', error);
                });
          }
        } else {
          console.log('输入数据有误！');
          return false;
        }
      });
    }
  },
  mounted() {
    this.fetchEvents();
  }
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}
</style>
